<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="上下架" prop="bannerStatus">
        <el-select v-model="queryParams.bannerStatus" placeholder="请选择上下架" clearable size="small">
          <el-option
            v-for="dict in bannerStatusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择开始时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="过期时间" prop="expireTime">
        <el-date-picker
          clearable
          size="small"
          style="width: 200px"
          v-model="queryParams.expireTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择过期时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:banner:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:banner:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:banner:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:banner:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="过期时间" align="center" prop="id" />
      <el-table-column label="跳转地址" align="center" prop="url" />
      <el-table-column label="描述" align="center" prop="detail" />
      <el-table-column label="图片" :show-overflow-tooltip="true" align="center" prop="imageUrl" />
      <el-table-column
        label="上下架"
        align="center"
        prop="bannerStatus"
        :formatter="bannerStatusFormat"
      />
            <el-table-column
        label="是否是H5"
        align="center"
        prop="bannerStatus"
        :formatter="h5StatusFormat"
      />
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="过期时间" align="center" prop="expireTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:banner:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:banner:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改前台banner对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="跳转地址" prop="url">
          <el-input v-model="form.url" placeholder="请输入跳转地址" />
          <code>示例：page/video/index?id=12</code>
        </el-form-item> -->
        <el-form-item label="描述" prop="detail">
          <el-input v-model="form.detail" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="排序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <!--          <el-input v-model="form.url" placeholder="请输入分类icon" />-->
          <el-upload
            :headers="videoUpload.headers"
            :action="videoUpload.url"
            :file-list="poster"
            :before-upload="limit_1"
            list-type="picture-card"
            :on-success="handlePagePhotoSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handlePagePhotoRemove"
            accept=".jpg, .jpeg, .png, , .JPG, .JPEG"
            :limit="1"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="banner图片" prop="detail">
          <el-input v-model="form.imageUrl" placeholder="自动生成图片地址" readonly />
        </el-form-item>
        <el-form-item label="上下架">
          <el-radio-group v-model="form.bannerStatus">
            <el-radio
              v-for="dict in bannerStatusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
                <el-form-item label="是否是H5">
          <el-radio-group v-model="form.isH5">
            <el-radio
              v-for="dict in h5StatusOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="form.isH5==1"> <el-form-item label="H5地址" prop="url">
          <el-input v-model="form.url" placeholder="H5地址" />
        </el-form-item></div>
          <div  v-if="form.isH5==0">
               <el-form-item label="小程序路由" prop="url">
          <el-input v-model="form.url" placeholder="小程序路由" />
        </el-form-item>
          </div>
       
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="过期时间" prop="expireTime">
          <el-date-picker
            clearable
            size="small"
            style="width: 200px"
            v-model="form.expireTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择过期时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBanner,
  getBanner,
  delBanner,
  addBanner,
  updateBanner,
  exportBanner
} from "@/api/content/banner";
import { getToken } from "@/utils/auth";
export default {
  name: "Banner",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 前台banner表格数据
      bannerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 上下架字典
      bannerStatusOptions: [],
         h5StatusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bannerStatus: undefined,
        startTime: undefined,
        expireTime: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        detail: [{ required: true, message: "必填项目", trigger: "blur" }],
        orderNum: [{ required: true, message: "必填项目", trigger: "blur" }],
        startTime: [{ required: true, message: "必填项目", trigger: "blur" }],
        expireTime: [{ required: true, message: "必填项目", trigger: "blur" }],
        url: [{ required: true, message: "必填项目", trigger: "blur" }]
      },
      videoUpload: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/sys/file/upload",
        url2: process.env.VUE_APP_BASE_API
      },
      poster: [],
      t1: []
    };
  },
  created() {
    this.getList();
    this.getDicts("sys_on_status").then(response => {
      this.bannerStatusOptions = response.data;
    });
       this.getDicts("plat_is_h5").then(response => {
      this.h5StatusOptions = response.data;
    });
  },
  methods: {
    /** 查询前台banner列表 */
    getList() {
      this.loading = true;
      listBanner(this.queryParams).then(response => {
        this.bannerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 上下架字典翻译
    bannerStatusFormat(row, column) {
      return this.selectDictLabel(this.bannerStatusOptions, row.bannerStatus);
    },
        h5StatusFormat(row, column) {
      return this.selectDictLabel(this.h5StatusOptions, row.isH5);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
     this.form = {
        id: undefined,
        url: undefined,
        detail: undefined,
        orderNum: undefined,
        imageUrl: undefined,
        bannerStatus: "0",
        startTime: undefined,
        expireTime: undefined,
        xcxUrl:undefined,
        isH5:undefined
      };
      this.poster = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
       this.poster =[];
      this.t1 = [];
      this.open = true;
      this.title = "添加前台banner";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.poster =[];
      this.t1 = [];
      this.poster = []
      const id = row.id || this.ids;
      getBanner(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改前台banner";
        var vm = new Array();
        vm.push(response.data.imageUrl);
        this.poster = vm.map(item => {
          return {
            url: item
          };
        });
        this.t1 = [];
        this.t1.push(response.data.imageUrl);
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (this.poster.length == 0) {
          this.msgError("请选择图片上传");
          return;
        }
        console.log(this.t1);
        this.form.imageUrl = this.t1[0];
        if (valid) {
          if (this.form.id != undefined) {
            updateBanner(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addBanner(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除前台banner编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delBanner(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有前台banner数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(function() {
          return exportBanner(queryParams);
        })
        .then(response => {
          this.download(response.msg);
        })
        .catch(function() {});
    },
    handlePagePhotoRemove(file, fileList) {
      console.log("移除");
      console.log(fileList);
      console.log(file);
      this.poster = fileList;
      this.t1 = [];
      this.form.imageUrl = null
      for (var i = 0; i < fileList.length; i++) {
        this.t1.push(fileList[i].url);
      }
    },

    handlePagePhotoSuccess(res, file) {
      console.log(file);
      this.poster.push(file);
      this.form.imageUrl = file.response.url;
      this.t1.push(file.response.url);
    },
    handlePictureCardPreview(file) {
      console.log("预览");
    },
    getUrl(v) {
      if (v.length == 0) {
        return null;
      }
      var arr = new Array();
      for (var i = 0; i < v.length; i++) {
        if (v[i].response == null || v[i].response == undefined) {
          arr.push(v[i].url);
        } else {
          arr.push(v[i].response);
        }
      }
      return arr;
    },
    limit_1(file) {
      this.msgInfo("不能大于1张");
    }
  }
};
</script>
